#!/usr/bin/env python

import sys
import mail
import os
import zipfile

def getImportantLine(lines):
    for i in range(len(lines)):
        if lines[i] in ('BUILD FAILED', 'BUILD SUCCESSFUL'):
            return i
    return -1

def zipIt(filename):
    zFileName = filename + '.zip'
    zFile = zipfile.ZipFile(zFileName,
                              mode='w',
                              compression=zipfile.ZIP_DEFLATED)
    zFile.write(filename)
    zFile.close()
    return zFileName

def main(args=None):
    if args == None:
        args = sys.argv[1:]

    if len(args) < 4:
        print 'Usage:', os.path.basename(sys.argv[0]), '<logfile> <project> <branch> <to> [<to> ...]'
        return 1

    logfile = args[0]
    project = args[1]
    branch = args[2]
    toAddresses = args[3:]
    
    tail = map(str.strip, file(logfile).readlines()[-10:])

    importantLineNumber = getImportantLine(tail)
    if 'BUILD SUCCESSFUL' == tail[importantLineNumber]:
        subject = ' '. join((project, branch, 'build successful'))
    else:
        subject = ' '. join((project, branch, 'build failed'))

    body = '\n'.join(tail[importantLineNumber:])

    zFileName = zipIt(logfile)
    
    m = mail.MailSender()
    m.send(mail.username() + '@mitra.com',  toAddresses, subject, body, [zFileName])

    return 0


if __name__ == '__main__':
    sys.exit(main())

